<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/iron-collapse/iron-collapse.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../bower_components/paper-spinner/paper-spinner.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<dom-module id="metric-menu">
    <template>
        <style include="shared-styles">
         :host {
            position: relative;
            outline: none;
            cursor: pointer;
        }
        paper-item {
            cursor: pointer;
        }
        iron-collapse {
            margin-left: 16px;
        }
        </style>

        <template is="dom-if" if="[[metric.options.length]]">
            <paper-item on-tap="toggle">[[metric.name]] <iron-icon icon="icons:expand-more"></iron-icon></paper-item>
            <iron-collapse id="collapse">
                <template is="dom-repeat" items="[[metric.options]]">
                    <metric-menu machine="[[machine]]" metric="[[item]]"></metric-menu>
                </template>
            </iron-collapse>
        </template>

        <template is="dom-if" if="[[!metric.options.length]]">
            <paper-item on-tap="addGraph">[[metric.name]] </paper-item>
        </template>

        <iron-ajax id="associateMetric" handle-as="xml" method="PUT" contentType="application/json" loading="{{loadingMetrics}}" on-response="_handleAssociateResponse" on-error="_handleAssociateError">
        </iron-ajax>

    </template>
    <script>
    Polymer({
        is: "metric-menu",
        properties: {
            metric: {
                type: Object
            },
            machine: {
                type: String
            }
        },
        toggle: function(e) {
            this.shadowRoot.querySelector('iron-collapse').toggle();
        },
        addGraph: function(e) {
            console.log('addGraph', this.machine);
            document.querySelectorAll('vaadin-dialog-overlay').forEach(function(el){el.opened = false;})
            var metric = this.metric.name;
            var payload = {
                metric_id: metric
            };
            this.$.associateMetric.url = "/api/v1/machines/" + this.machine + "/metrics";
            this.$.associateMetric.headers["Csrf-Token"] = CSRF_TOKEN;
            this.$.associateMetric.params = payload;
            this.$.associateMetric.generateRequest();
        },
        _handleAssociateResponse: function(e) {
            console.log('event in add-graph');
            e.stopPropagation();
            document.querySelector('mist-app').fire('update-dashboard');
        }
    });
    </script>
</dom-module>